<template>
    <div id="RiskPoint" class="w-h-100 pos-r flex-1 apply-container page-public-s" style="box-sizing: border-box;overflow:hidden;">
        <div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px;">
            <div v-if="$hasPer('RiskPoint:add') || $hasPer('RiskPoint:excel')" style="box-sizing: border-box;">
                <el-card shadow="never" :body-style="{ paddingBottom: '0' }">
                    <el-form class="box-f" ref="queryForm" :inline="true">
                        <el-form-item >
                            <el-button v-if="$hasPer('RiskPoint:add')" @click="nodeClick('','add')" icon="ele-Plus" type="primary"> 新增 </el-button>
                            <el-button v-if="$hasPer('RiskPoint:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
                            <!-- <el-button  @click="batchHandle(1,getData)" icon="ele-Refresh" type="primary"> 批量启用 </el-button>
                            <el-button  @click="batchHandle(2,getData)" icon="ele-Refresh" type="primary"> 批量停用 </el-button> -->
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>

            <div style="box-sizing: border-box;" class="flex-1 pos-r">
                <div class="pos-a w-h-100" style="box-sizing: border-box;">
                    <el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px;">
                        <div style="" class="w-h-100 ver-flex">
                            <div class="flex-1 pos-r">
                                <div class="pos-a w-h-100">
                                    <el-table 
                                        ref="excelRef"
                                        :data="list" 
                                        class="w-h-100" 
                                        style="width: 100%" 
                                        border 
                                        v-loading="loading" 
                                        element-loading-background="rgba(0, 0, 0, 0.5)"
                                        @selection-change="handleSelectionChange"
                                    >

                                        <!-- <el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" /> -->
                                        <!-- <el-table-column type="selection" width="55" /> -->

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="风险分析单元名称"  align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="i_Name" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.v_Name">{{ scope.row.v_Name }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="风险分析单元类型"  align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="s_Type" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span style="color: #67C23A;" v-if="scope.row.n_Type === 0">{{ scope.row.v_TypeName }}</span>
                                                    <span style="color: #E6A23C;" v-if="scope.row.n_Type === 1">{{ scope.row.v_TypeName }}</span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" prop="" label="所属风险分区名称"  align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="s_Risk" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.v_RiskPartitionName">{{ scope.row.v_RiskPartitionName }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="责任部门名称"  align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="s_Dep" typeVal="cascader" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.v_ResponsibleDepName">{{ scope.row.v_ResponsibleDepName }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="责任人"  align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="i_Man" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.v_ResponsibleMan">{{ scope.row.v_ResponsibleMan }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" prop="v_ResponsibleMan" label="启用状态"  align="center">
                                            <template #default="scope">
                                                <span v-if="scope.row.isUse" style="color: #67C23A;">启用</span>
                                                <span v-if="!scope.row.isUse" style="color: #FC5400;">停用</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="风险评价方法"  align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="s_Method" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.v_EvaluationMethod">{{ scope.row.v_EvaluationMethod }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="风险等级"  align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <SearchModel typeId="s_Level" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.n_RiskLevel === 0" style="color: #67C23A;">{{ scope.row.v_RiskLevelName }}</span>
                                                    <span v-if="scope.row.n_RiskLevel === 1" style="color: #E6A23C;">{{ scope.row.v_RiskLevelName }}</span>
                                                    <span v-if="scope.row.n_RiskLevel === 2" style="color: #CE7C01;">{{ scope.row.v_RiskLevelName }}</span>
                                                    <span v-if="scope.row.n_RiskLevel === 3" style="color: #FC5400;">{{ scope.row.v_RiskLevelName }}</span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" prop="n_EventCount" label="风险事件数量"  align="center" sortable />

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" prop="n_DCListCount" label="危害因数数量"  align="center" sortable />

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="设备/作业活动"  align="center" fixed="right">
                                            <template #default="scopes">
                                                <el-popover :visible.sync="scopes.row.isVisible" placement="bottom" width="50%">
                                                    <template #reference>
                                                        <el-button v-if="scopes.row.n_Type === 0" @click="viewClick(scopes.row)" class="icon-e" icon="ele-Edit" text type="warning">设备类操作</el-button>
                                                        <el-button v-if="scopes.row.n_Type === 1" @click="viewClick(scopes.row)" class="icon-e" icon="ele-Edit" text type="primary">作业类操作</el-button>
                                                    </template>
                                                    <div class="search-s">
                                                        <div class="search-s-l">
                                                            <!-- <el-input style="width: 40%;margin-right: 10px;" class="search-inp" v-model="filterSearch" placeholder="请输入名称" />
                                                            <el-button @click='activeClick(0,)' icon="ele-Search" type="primary"> 查询 </el-button>
                                                            <el-button  @click="activeClick(1)" icon="ele-Refresh"> 重置 </el-button> -->
                                                            <el-button v-if="$hasPer('RiskPoint:addEqu') && scopes.row.n_Type === 0" @click="activeClick(2,scopes.row)" icon="ele-Plus" type="primary"> 新增 </el-button>
                                                            <el-button v-if="$hasPer('RiskPoint:addJob') && scopes.row.n_Type === 1" @click="activeClick(2,scopes.row)" icon="ele-Plus" type="primary"> 新增 </el-button>
                                                        </div>
                                                        <el-button @click="closeHandle(scopes.row)" class="icon-e" icon="ele-CloseBold" text type="primary">关闭</el-button>
                                                    </div>
                                                    <div v-if="scopes.row.n_Type === 0">
                                                        <el-table :data="gridData" v-loading="gridLoading" border>
                                                            <el-table-column min-width="120" label="设备名称" :show-overflow-tooltip="true"  align="center">
                                                                <template #default="scopes">
                                                                    <span>{{ scopes.row.v_Name }}</span>
                                                                </template>
                                                            </el-table-column>
                                                            <el-table-column min-width="120" label="规格型号" :show-overflow-tooltip="true"  align="center">
                                                                <template #default="scopes">
                                                                    <span>{{ scopes.row.v_SpeciModel }}</span>
                                                                </template>
                                                            </el-table-column>
                                                            <el-table-column min-width="120" label="运行时间(小时)" :show-overflow-tooltip="true"  align="center">
                                                                <template #default="scopes">
                                                                    <span>{{ scopes.row.n_RunTime }}</span>
                                                                </template>
                                                            </el-table-column>
                                                            <el-table-column min-width="120" label="服务区域" :show-overflow-tooltip="true"  align="center">
                                                                <template #default="scopes">
                                                                    <span>{{ scopes.row.v_ServiceArea }}</span>
                                                                </template>
                                                            </el-table-column>
                                                            <el-table-column min-width="120" label="安装位置" :show-overflow-tooltip="true"  align="center">
                                                                <template #default="scopes">
                                                                    <span>{{ scopes.row.v_Location }}</span>
                                                                </template>
                                                            </el-table-column>
                                                            <el-table-column min-width="120" label="安装位置" :show-overflow-tooltip="true"  align="center">
                                                                <template #default="scopes">
                                                                    <span>{{ scopes.row.v_Location }}</span>
                                                                </template>
                                                            </el-table-column>
                                                            <el-table-column v-if="$hasPer('RiskPoint:delEqu')" min-width="140" prop="v_Remark" label="操作" :show-overflow-tooltip="true" align="center">
                                                                <template #default="scope">
                                                                    <!-- <el-button @click="detailHandle(scope.row.id)" class="icon-e" icon="ele-View" size="small" text type="success">详情</el-button> -->
                                                                    <!-- <el-button @click="activeClick(3,scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary">编辑</el-button> -->
                                                                    <el-button @click="activeClick(5,scope.row.id)" class="icon-e" icon="ele-Delete" size="small" text type="danger">删除</el-button>
                                                                </template>
                                                            </el-table-column>
                                                        </el-table>
                                                    </div>
                                                    <div v-if="scopes.row.n_Type === 1">
                                                        <el-table :data="gridData" v-loading="gridLoading" border>
                                                            <el-table-column min-width="120" prop="v_Name" label="作业活动名称" :show-overflow-tooltip="true"  align="center" />
                                                            <el-table-column min-width="120" prop="v_Kind" label="作业类别" :show-overflow-tooltip="true"  align="center" />
                                                            <el-table-column min-width="80" prop="v_FrequencyName" label="作业频率" :show-overflow-tooltip="true"  align="center" />
                                                            <el-table-column min-width="120" prop="v_PostName" label="岗位名称" :show-overflow-tooltip="true"  align="center" />
                                                            <el-table-column min-width="140" prop="v_Remark" label="备注" :show-overflow-tooltip="true"  align="center">
                                                                <template #default="scope">
                                                                    <span v-if="scope.row.v_Remark">{{ scope.row.v_Remark }}</span>
                                                                    <span v-else>-</span>
                                                                </template>
                                                            </el-table-column>
                                                            <el-table-column v-if="$hasPer('RiskPoint:editJob') || $hasPer('RiskPoint:delJob')" min-width="140" prop="v_Remark" label="操作" :show-overflow-tooltip="true" align="center">
                                                                <template #default="scope">
                                                                    <!-- <el-button @click="detailHandle(scope.row.id)" class="icon-e" icon="ele-View" size="small" text type="success">详情</el-button> -->
                                                                    <el-button v-if="$hasPer('RiskPoint:editJob')" @click="activeClick(3,scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary">编辑</el-button>
                                                                    <el-button v-if="$hasPer('RiskPoint:delJob')" @click="activeClick(4,scope.row.id)" class="icon-e" icon="ele-Delete" size="small" text type="danger">删除</el-button>
                                                                </template>
                                                            </el-table-column>
                                                        </el-table>
                                                    </div>
                                                    
                                                    <!-- <el-pagination
                                                        v-model:currentPage="activePageNo"
                                                        v-model:page-size="activePageSize"
                                                        :total="activeTotalRows"
                                                        :page-sizes="[10, 20, 50, 100]"
                                                        small
                                                        background
                                                        @size-change="activeHandleSizeChange"
                                                        @current-change="activeHandleCurrentChange"
                                                        layout="total, sizes, prev, pager, next, jumper"
                                                        class="w-h-100"
                                                    /> -->
                                                </el-popover>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="180" :show-overflow-tooltip="true" prop="createdTime" label="创建时间"  align="center" sortable>
                                            <template #default="scope">
                                                <span v-if="scope.row.createdTime">{{ scope.row.createdTime }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="180" :show-overflow-tooltip="true" prop="updatedTime" label="更新时间"  align="center" sortable>
                                            <template #default="scope">
                                                <span v-if="scope.row.updatedTime">{{ scope.row.updatedTime }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="200" label="操作" align="center" fixed="right">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200" align="center">
                                                <template #header>
                                                    <el-button class="icon-e" @click='searchClick' icon="ele-Search" size="small" type="primary" text> 查询 </el-button>
                                                    <el-button class="icon-e clear-bg" style="background-color: transparent !important;" size="small" @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
                                                </template>
                                                <template #default="scope">
                                                    <div class="operate-s">
                                                        <el-button @click="detailHandle(scope.row.id)" class="icon-e" icon="ele-View" size="small" text type="success">详情</el-button>
                                                        <el-button v-if="$hasPer('RiskPoint:edit')" @click="nodeClick(scope.row,'edit')" class="icon-e" icon="ele-Edit" size="small" text type="primary">编辑</el-button>
                                                        <el-button v-if="$hasPer('RiskPoint:del')" @click="deleteHandle(scope.row.id, getData)" class="icon-e" icon="ele-Delete" size="small" text type="danger">删除</el-button>
                                                        <!-- <el-button v-if="!scope.row.isUse" @click="documentClick(scope.row,1 ,getData)" class="icon-e" icon="ele-Discount" size="small" text type="primary">是否启用</el-button>
                                                        <el-button v-if="scope.row.isUse" @click="documentClick(scope.row,2, getData)" class="icon-e" icon="ele-Discount" size="small" text type="warning">是否停用</el-button> -->
                                                    </div>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                    </el-table>
                                </div>
                            </div>
                            <div style="height: 30px;margin-top: 20px;" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
                        </div>
                    </el-card>
                </div>
            </div>
        </div>
        <AddEditRiskPoint
            :repairInfo="repairInfo"
            :isUseDialog="isUseDialog"
            @updateData="getData"
            @cancelUseClick="cancelUseClick"
            @controlUseClick="controlUseClick"
        />
        <AddEditActive
            :rowInfo="rowInfo"
            :currentStatus="currentStatus"
            :repairInfo="activeInfo"
            :isUseDialog="activeDialog"
            @cancelActiveClick="cancelActiveClick"
            @controlActiveClick="controlActiveClick"
        />
        <!-- 详情 -->
        <DetailModel
            :detailInfo="detailInfo"
            :MdetailDialog="MdetailDialog"
            labelWidth="140px"
            :imgSrc="imgSrc"
            @cancelDetailClick="cancelDetailClick"
        />
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, Ref, onMounted , reactive , toRaw } from 'vue';
import getTableData from '/@/utils/getTableData';
import { 
    SMSDCAnalysisUnitPage , 
    SMSDCAnalysisUnitDelete , 
    SMSDCAnalysisUnitJobPage , 
    SMSDCAnalysisUnitUpdateIsUse , 
    SMSDCAnalysisUnitBathUpdateIsUse , 
    SMSDCAnalysisUnitJobDelete,
    SMSDCAnalysisUnitMachineDelete,
    SMSDCAnalysisUnitMachinePage,
    sysDictDataList,
    SMSDCRiskPartitionList,
    SMSDCAnalysisUnitDetail,
 } from '/@/api/centerControl/sms';
import AddEditRiskPoint from '../component/sms/add-edit-RiskPoint.vue';
import AddEditActive from '../component/sms/add-edit-active.vue';
import { ElMessageBox , ElMessage } from 'element-plus';
import { sysOrgTree , sysFileInfoPage } from '/@/api/centerControl/pubilc';
import SearchModel from '../component/search-model.vue';
import DetailModel from '../component/detail-model.vue';
import { exportToExcel } from '/@/utils/exportToExcel';
import QRCode from 'qrcode';

export default defineComponent( {
    name: 'RiskPoint',
    components: {
        AddEditRiskPoint,
        AddEditActive,
        SearchModel,
        DetailModel,
    },
    setup(props){
        const isUseDialog = ref() // 新增/编辑弹出框隐藏/显示
        const repairInfo = ref() // 传递子组件数据
        const gridData = ref();
        const filterSearch = ref();
        const activeInfo = ref();
        const activeDialog = ref(false);
        const rowInfo: any = ref('');
        const gridLoading = ref(false);

        const activePageNo = ref(1);
        const activePageSize = ref(10);
        const activeTotalRows = ref(0);
        let isRefactoring =  false; // 用户执行删除的时候判断是否需要重构数据
        let worlkId = 0;
        
        const currentStatus = ref();
        let multipleSelection: any = [];

        /*** nodeClick 新增/编辑点击事件 */
        const nodeClick = (val:string | object , am:string) => {
            val !== '' ? repairInfo.value = JSON.stringify(toRaw(val)) : repairInfo.value = ''
            isUseDialog.value = true
        };

        /*** deleteHandle 删除数据事件 */
        const deleteHandle = async (val: String | Number, updateFun: Function) => {
            ElMessageBox.confirm('请确定删除此条数据？','提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
            .then(async() => {
                let param = {id : val};
                try {
                    let res:any = await SMSDCAnalysisUnitDelete(param);
                    if(res.success){
                        updateFun()
                    }
                } catch (err) { return }
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '已取消',
                })
            })
        };

        /*** viewClick 页中页数据 */
        const viewClick = (val:any) => {
            worlkId = val.id;
            val.isVisible = true;
            rowInfo.value = JSON.stringify(val);
            setTimeout(() => {
                getWorlkFun(val.id);
            }, 0);
        }

        /*** getWorlkFun 获取作业活动数据 */
        const getWorlkFun = async(id:number) => {
            gridLoading.value = true;
            gridData.value = [];
            let param: any = {};
            let res: any;
            param.l_AnalysisUnitId = id;
            param.pageNo = activePageNo.value;
            param.pageSize = activePageSize.value;
            if(rowInfo.value !== '' && JSON.parse(rowInfo.value).n_Type === 0) res = await SMSDCAnalysisUnitMachinePage(param);
            if(rowInfo.value !== '' &&JSON.parse(rowInfo.value).n_Type === 1) res = await SMSDCAnalysisUnitJobPage(param);
            if(res.success){
                activeTotalRows.value = res.data.totalRows;
                let item = res.data.rows;
                if(item.length === 1){
                    isRefactoring = true;
                }else{
                    isRefactoring = false;
                }
                if(item.length !== 0){
                    if(JSON.parse(rowInfo.value).n_Type === 0) {
                        let setArr: any = [];
                        item.map((i: any) => {
                            i.equipmentInfo.id = i.id;
                            i.equipmentInfo.v_Names = i.equipmentInfo.v_Name;
                            i.equipmentInfo.l_MachineId = i.l_MachineId;
                            i.equipmentInfo.v_AnalysisUnitName = i.v_AnalysisUnitName;
                            setArr.push(i.equipmentInfo);
                        });
                        let setTime = setInterval(() => {
                            if(setArr.length !== 0){
                                gridData.value = setArr;
                                clearInterval(setTime);
                            }
                        },50);
                    }else{
                        gridData.value = item;
                    }
                }
            }
            gridLoading.value = false;
        }

        /*** closeHandle 关闭弹出组件 */
        const closeHandle = (val: any) => {
            val.isVisible = false;
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            isUseDialog.value = false
        };

        /*** controlUseClick 提交事件 */
        const controlUseClick = () => {
            isUseDialog.value = false
        };
        
        /*** documentClick 单条数据启用/停用 */
        const documentClick = (val:any, num: number , uploadFun: Function) => {
            let setBoole:any;
            if(num === 1){
                setBoole = true;
            }else{
                setBoole = false;
            }
            let param:any = {};
            param.id = val.id;
            param.isUse = setBoole;
            startEndFun(1,JSON.stringify(param),uploadFun);
        }
        /*** batchHandle 批量启用/停用 */
        const batchHandle = (num: number , uploadFun: Function) => {
            let param: any = {};
            let setBoole:any;
            let setArr:any = [];
            if(multipleSelection.length === 0){
                ElMessage({
                    type: 'warning',
                    message: '请选择需要更新的数据',
                });
                return;
            }else{
                multipleSelection.map((item: any) => {
                    setArr.push(item.id);
                });
                param.l_Ids = setArr;
            }
            if(num === 1){
                setBoole = true;
            }else{
                setBoole = false;
            }
            param.isUse = setBoole;
            startEndFun(2,JSON.stringify(param),uploadFun)
        }
        /*** startEndFun 启用/停用函数 */
        const startEndFun = async(num: number, val: any , uploadFun: Function) => {
            let param = JSON.parse(val);
            let res:any;
            if(num === 1){
                res = await SMSDCAnalysisUnitUpdateIsUse(param);
            }else{
                res = await SMSDCAnalysisUnitBathUpdateIsUse(param);
            }
            if(res.success) uploadFun();
        }
        /*** handleSelectionChange 批量更新的复选框 */
        const handleSelectionChange = (val: any) => {
            multipleSelection = val;
        }

        /*** activeClick 作业活动各类点击事件 */
        const activeClick = (num: number, val?: any) => {
            switch(num){
                case 0:
                    console.log(filterSearch.value,'filterSearch')
                    // 查询
                    break;
                case 1:
                    filterSearch.value = '';
                    getWorlkFun(worlkId);
                    // 重置
                    break;
                case 2:
                    // 新增
                    if(gridData.value.length === 0){
                        currentStatus.value = 'add';
                        activeInfo.value = JSON.stringify(val);
                        activeDialog.value = true;
                    }else{
                        ElMessage({
                            type: 'warning',
                            message: '已有数据无需新增',
                        })
                    }
                    break;
                case 3:
                    // 编辑
                    currentStatus.value = 'edit';
                    activeInfo.value = JSON.stringify(val);
                    activeDialog.value = true;
                    break;
                case 4:
                    // 删除作业
                    activeDeleteFun(val);
                    break;
                case 5:
                    // 删除设备
                    activeDeleteJobFun(val);
                    break;
            }

        }
        /*** activeDeleteFun 删除设备记录事件 */
        const activeDeleteJobFun = (id:Number) => {
            ElMessageBox.confirm('请确定删除此条数据？','提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
            .then(async() => {
                if(isRefactoring){
                    if(activePageNo.value > 1){
                        activePageNo.value -= 1
                    }
                }
                let param = {id : id}
                try {
                    let res:any = await SMSDCAnalysisUnitMachineDelete(param);
                    if(res.success){
                        getWorlkFun(worlkId);
                    }
                } catch (err) { return }
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '已取消',
                })
            })
        }
        /*** activeDeleteFun 作业活动删除记录事件 */
        const activeDeleteFun = (id:Number) => {
            ElMessageBox.confirm('请确定删除此条数据？','提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
            .then(async() => {
                if(isRefactoring){
                    if(activePageNo.value > 1){
                        activePageNo.value -= 1
                    }
                }
                let param = {id : id}
                try {
                    let res:any = await SMSDCAnalysisUnitJobDelete(param);
                    if(res.success){
                        getWorlkFun(worlkId);
                    }
                } catch (err) { return }
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '已取消',
                })
            })
        }
        /*** cancelActiveClick 作业活动取消事件 */
        const cancelActiveClick = () => {
            activeDialog.value = false;
        };
        /*** controlActiveClick 作业活动提交事件 */
        const controlActiveClick = () => {
            getWorlkFun(worlkId);
            activeDialog.value = false;
        };
        
        const activeHandleSizeChange = (val: any) => {
            // 每页的总数据
            activePageNo.value = 1;
            activePageSize.value = val;
            getWorlkFun(worlkId);
        }
        const activeHandleCurrentChange = (val: any) => {
            // 当前处于第几页
            activePageNo.value = val;
            getWorlkFun(worlkId);
        }

        /*** ================================= 详情类数据操作 =================================  */
        const MdetailDialog = ref(false);
        const detailInfo = ref();
        const imgSrc = ref('');

        // 获取文件
        const getFileFun = async (sourceId: number) => {
            let param: any = {};
            param.PageNo = 1;
            param.PageSize = 99999;
            param.sourceId = sourceId;
            let res: any = await sysFileInfoPage(param);
            if(res.success) return res.data.rows;
        }
        /*** 生成二维码 */
        const generateQRCode = (val: any) => {
            if(val){
                QRCode.toDataURL(val).then((url: any) => {
                    imgSrc.value = url;
                }).catch((err: any) => {
                    console.error(err);
                });
            }else{
                imgSrc.value = "";
            }
        }
        /*** 获取详情接口数据 */
        const getDetailFun = async (id: number) => {
            let res: any = await SMSDCAnalysisUnitDetail({id: id}); // 详情
            if(res.success){
                let setArr: any = [];
                let tableArr: any = [];
                let detailObjOne: any = {};
                let detailObjTwo: any = {};
                console.log(res.data,'res.data')
                let jobObj = res.data.jobApplyInfo;
                if(jobObj && Object.keys(jobObj).length !== 0){
                    await getFileFun(jobObj.l_FileId).then((item: any) => {
                        if(item.length !== 0){
                            item.map((val: any) => {
                                let itemObj: any = {};
                                itemObj['id'] = val.id;
                                itemObj['fileObjectName'] = val.fileObjectName;
                                itemObj['附件名称'] = val.fileOriginName;
                                itemObj['文件格式'] = val.fileSuffix;
                                itemObj['文件大小'] = val.fileSizeKb;
                                itemObj['文件路径'] = val.filePath;
                                tableArr.push(itemObj);
                            });
                        }
                    });
                    detailObjTwo['作业类型'] = jobObj.v_JobType;
                    detailObjTwo['承包商'] = jobObj.v_ProviderName;
                    detailObjTwo['动工地点'] = jobObj.v_JobAddress;
                    detailObjTwo['计划动工开始日期'] = jobObj.d_IntendedStartTime;
                    detailObjTwo['计划完工日期'] = jobObj.d_IntendedCompletionTime;
                    detailObjTwo['动工内容'] = jobObj.v_JobContent;
                    detailObjTwo['项目名称'] = jobObj.v_ProjectName;
                    detailObjTwo['作业申请编号'] = jobObj.v_ApplyNO;
                    detailObjTwo['申请人员'] = jobObj.v_ApplyEmpName;
                    detailObjTwo['审核状态'] = jobObj.v_FlowinstanceStateName;
                    setArr.push({
                        formTitle: '申请作业基础信息',
                        type: 'form',
                        info: detailObjTwo,
                    },{
                        tableTitle: '作业文档数据',
                        type: 'table',
                        listData: tableArr,
                        minWidth: 160,
                        isShowBtn: true,
                    });
                }
                detailObjOne['风险分析单元名称'] = res.data.v_Name ? res.data.v_Name : '-';
                detailObjOne['风险分析单元分类'] = res.data.v_TypeName;
                detailObjOne['所属风险分区'] = res.data.v_RiskPartitionName;
                detailObjOne['责任部门'] = res.data.v_ResponsibleDepName;
                detailObjOne['责任人'] = res.data.v_ResponsibleMan ? res.data.v_ResponsibleMan : '-';
                detailObjOne['是否启用'] = res.data.isUse ? '启用' : '禁用';
                detailObjOne['风险评价方法'] = res.data.v_EvaluationMethod;
                detailObjOne['风险等级'] = res.data.v_RiskLevelName;
                detailObjOne['风险事件数量(个)'] = res.data.n_EventCount;
                detailObjOne['危害因数数量(个)'] = res.data.n_DCListCount;
                detailObjOne['设备二维码'] = res.data.v_DCQRCode ? res.data.v_DCQRCode : '-';
                if(res.data.v_DCQRCode) generateQRCode(res.data.v_DCQRCode);
                setArr.push({
                    formTitle: '分析单元基础信息',
                    type: 'form',
                    info: detailObjOne,
                });
                detailInfo.value = setArr;
                MdetailDialog.value = true;
            }
        }
        /*** 详情 */
        const detailHandle = (id: number) => {
            getDetailFun(id);
        }
        /*** 详情关闭事件 */
        const cancelDetailClick = () => {
            MdetailDialog.value = false;
        }
        /*** ================================= 详情类数据操作 =================================  */
        
        /*** ================================= 查询类数据操作 =================================  */
        let searchObj:any = reactive({});
        const basicsInfo: any = ref([]);
        const searInfo: any = ref();

        /*** 获取需要查询的数据 */
        const searchHandel = (val: any) => {
            searInfo.value = val;
        }

        /*** 查询按钮 */
        const searchClick = () => {
            let newObj = Object.keys(searInfo.value);
            if(newObj.length !== 0){
                newObj.map((i:any) => {
                    searchObj[i] = searInfo.value[i];
                });
            }
        };

        /*** 重置按钮 */
        const resetClick = () => {
            searInfo.value = {};
            let newObj = Object.keys(searchObj);
            if(newObj.length !== 0){
                newObj.map((i:any) => {
                    searchObj[i] = ''
                });
            }
            initInfoFun();
        };

        let depArr: any = [];
        let riskArr: any = [];
        let methodArr: any = [];
        // 获取数据
        const getFun = async () => {            
            let ras: any = await sysOrgTree({}); // 获取组织架构列表
            let rbs: any = await sysDictDataList({TypeCode: 'SmsEvaluate'}); // 风险评价方法
            let rcs: any = await SMSDCRiskPartitionList({}); // 所属风险分区
            if(ras.success && ras.data.length !== 0) depArr = ras.data;
            if(rbs.success && rbs.data.length !== 0) {
                rbs.data.map((item: any) => {
                    item.label = item.value;
                    item.value = item.value;
                });
                methodArr = rbs.data;
            }
            if(rcs.success && rcs.data.length){
                console.log(rcs.data,'rcs')
                rcs.data.map((item: any) => {
                    item.label = item.v_Name;
                    item.value = item.id;
                });
                riskArr = rcs.data;
            }
        }
        
        /*** 初始化数据 */
        const initInfoFun = () => {
            basicsInfo.value = [{
                    typeId: 'i_Name', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'v_Name', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '分析单元名称', // placeholder数据
                    defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'burl', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: 'nameEvent', // 事件名称 --- 选填
                },{
                    typeId: 's_Risk', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'l_RiskPartitionId', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '所属风险分区', // placeholder数据
                    defaultProp: riskArr, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'change', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: 'areaChange', // 事件名称 --- 选填
                },{
                    typeId: 's_Dep', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'l_ResponsibleDepId', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '责任部门', // placeholder数据
                    defaultProp: depArr, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'change', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: 'depChange', // 事件名称 --- 选填
                    propsVal: { checkStrictly: true , label: 'title', value: 'id', children: 'children' }, // 级联选择器 --- 选填
                },{
                    typeId: 'i_Man', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'v_ResponsibleMan', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '负责人', // placeholder数据
                    defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'burl', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: 'manEvent', // 事件名称 --- 选填
                },{
                    typeId: 's_Type', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'n_Type', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '风险分析单元分类', // placeholder数据
                    defaultProp: [
                        {label: '设备类', value: 0},
                        {label: '作业活动类', value: 1},
                    ], // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'change', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: 'typeChange', // 事件名称 --- 选填
                },{
                    typeId: 's_Method', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'v_EvaluationMethod', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '风险评价方法', // placeholder数据
                    defaultProp: methodArr, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'change', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: 'mkethodChange', // 事件名称 --- 选填
                },{
                    typeId: 's_Level', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                    typeNam: '', // 输入类型(number,text等) --- 选填
                    searchVal: 'n_RiskLevel', // 查询字段 --- 必填
                    defaultVal: '', // 字段默认值 --- 选填
                    placeholder: '风险等级', // placeholder数据
                    defaultProp: [
                        {label: '低风险', value: 0},
                        {label: '一般风险', value: 1},
                        {label: '较大风险', value: 2},
                        {label: '重大风险', value: 3}
                    ], // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                    eventType: 'change', // 事件类型（如burl/change等） --- 选填
                    defaultEvent: 'levelChange', // 事件名称 --- 选填
                }
            ]
        }
        
        onMounted(async () => {
            await getFun();
            initInfoFun(); 
        });
        /*** ================================= 查询类数据操作 =================================  */

        /*** ================================= 导出数据函数操作 ================================= */
        const excelRef: any = ref(null);
        const handleExport = () => {
            if(excelRef){
                if(excelRef.value.data.length !== 0){
                    let tableExcel: any = [];
                    let tableArr = excelRef.value.data;
                    tableArr.map((item: any) => {
                        let tableObj: any = {};
                        tableObj['风险分析单元名称'] = item.v_Name ? item.v_Name : '-';
                        tableObj['风险分析单元分类'] = item.v_TypeName ? item.v_TypeName : '-';
                        tableObj['所属风险分区'] = item.v_RiskPartitionName ? item.v_TypeName : '-';
                        tableObj['责任部门'] = item.v_ResponsibleDepName ? item.v_TypeName : '-';
                        tableObj['责任人'] = item.v_ResponsibleMan ? item.v_ResponsibleMan : '-';
                        tableObj['是否启用'] = item.isUse ? '启用' : '禁用';
                        tableObj['风险评价方法'] = item.v_EvaluationMethod ? item.v_TypeName : '-';
                        tableObj['风险等级'] = item.v_RiskLevelName ? item.v_TypeName : '-';
                        tableObj['风险事件数量(个)'] = item.n_EventCount;
                        tableObj['危害因数数量(个)'] = item.n_DCListCount;
                        tableExcel.push(tableObj);
                    });
                    exportToExcel(tableExcel,'风险分析单元.xlsx');
                }else{
                    ElMessage({
                        type: 'error',
                        message: '暂无数据导出',
                    })
                }
            }
        }
        /*** ================================= 导出数据函数操作 ================================= */

        return {
            ...getTableData(SMSDCAnalysisUnitPage,{},searchObj),
            isUseDialog,
            cancelUseClick,
            controlUseClick,
            nodeClick,
            repairInfo,
            deleteHandle,
            documentClick,
            viewClick,
            gridData,
            filterSearch,
            activeClick,
            activeInfo,
            activeDialog,
            cancelActiveClick,
            controlActiveClick,
            closeHandle,
            rowInfo,
            gridLoading,
            
            activePageNo,
            activePageSize,
            activeTotalRows,
            activeHandleSizeChange,
            activeHandleCurrentChange,

            currentStatus,
            batchHandle,
            handleSelectionChange,

            // 导出Excel
            excelRef,
            handleExport,
            
            // 详情
            MdetailDialog,
            detailHandle,
            detailInfo,
            cancelDetailClick,
            imgSrc,

            // 查询事件
            basicsInfo,
            searchHandel,
            searchClick,
            resetClick,
        }
    },
} )
</script>
<style lang="scss"> @import '../style/public.scss'; </style>
<style scoped lang="scss">
    ul {
        list-style: none;
        li {
            cursor: pointer;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            text-align: center;
            padding: 10px 0;
        }
    }
    .search-s{
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        width: 100%;
        .search-s-l{
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            align-items: center;
            width: 98%;
        }
    }
    .box-f{
        :deep(.el-form-item__label){
            padding: 0;
        }
    }
    :deep(.el-card__body) {
        height: 100%;
    }
    :deep(.el-card){
        border: none !important;
    }
    .upload-demo{
        margin-left: 12px;
        margin-top: 2px;
    }
    .icon-e{
        :deep(.el-icon){
            margin-right: 0px!important;
        }
    }
.clear-bg{
    background-color: transparent !important;
}
</style>